<template>
  <div class="app-container">
    <div class="filter-container query">
      <el-form :model="listQuery" label-position="right" label-width="120px">
        <el-row :gutter="10">
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="企业名称" prop="companyId">
              <el-select v-model="listQuery.companyId" clearable filterable placeholder="请选择企业">
                <el-option
                  v-for="item in companyOptions"
                  :key="item.companyId"
                  :label="item.companyName"
                  :value="item.companyId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="站点编号" prop="stationNo">
              <el-input v-model="listQuery.stationNo" @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="站点名称" prop="stationName">
              <el-input v-model="listQuery.stationName" @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="归属省份" prop="province">
              <el-select v-model="listQuery.province" clearable filterable placeholder="请选择归属省份">
                <el-option
                  v-for="item in provinceOptions"
                  :key="item.province"
                  :label="item.province"
                  :value="item.province"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="归属城市" prop="city">
              <el-select v-model="listQuery.city" clearable filterable placeholder="请选择归属城市">
                <el-option
                  v-for="item in cityOptions"
                  :key="item.city"
                  :label="item.city"
                  :value="item.city"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="启用标记" prop="enableFlag">
              <el-select v-model="listQuery.enableFlag" clearable class="filter-item">
                <el-option v-for="item in enableFlagOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="站点类型" prop="stationType">
              <el-select v-model="listQuery.stationType" clearable class="filter-item">
                <el-option v-for="item in stationTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleFilter">
            搜索
          </el-button>
          <el-button class="filter-item" style="margin-left: 10px;" type="success" size="small" icon="el-icon-circle-plus-outline" @click="handleCreate">
            新增
          </el-button>
          <el-button type="info" icon="el-icon-refresh" size="small" @click="handleReset">
            重置
          </el-button>
          <el-button class="filter-item" type="danger" size="small" icon="el-icon-upload" @click="handleUpload">
            导入
          </el-button>
        </el-row>
      </el-form>
    </div>

    <el-table
      :loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;height: 100%;"
      size="small"
      @sort-change="sortChange"
    >
      <el-table-column label="操作" align="center" width="250">
        <template slot-scope="{row}">
          <el-button size="mini" type="primary" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
          <el-button size="mini" type="success" @click="handleAccounts(row)">
            账号
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="企业名称" prop="companyName" sortable="custom" width="250" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.companyName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="站点类型" prop="stationType" :formatter="formatter" width="90" header-align="center" align="center" />
      <el-table-column label="站点编号" prop="stationNo" sortable="custom" width="150" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.stationNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="站点名称" prop="stationName" sortable="custom" width="200" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.stationName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="站点地址" prop="stationAddress" sortable="custom" width="200" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.stationAddress }}</span>
        </template>
      </el-table-column>
      <el-table-column label="站点经度" prop="longitude" sortable="custom" width="100" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.longitude }}</span>
        </template>
      </el-table-column>
      <el-table-column label="站点纬度" prop="latitude" sortable="custom" width="100" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.latitude }}</span>
        </template>
      </el-table-column>
      <el-table-column label="归属省份" prop="province" sortable="custom" width="100" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.province }}</span>
        </template>
      </el-table-column>
      <el-table-column label="归属城市" prop="city" sortable="custom" width="100" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.city }}</span>
        </template>
      </el-table-column>
      <el-table-column label="启用标记" prop="enableFlag" :formatter="formatter" width="100" header-align="center" align="center" />
      <el-table-column label="创建时间" prop="createAt" width="160" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createAt }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageNoSize" size="small" @pagination="getList" />

    <el-dialog title="站点分配账号" :visible.sync="dialogTransferVisible" top="3vh" width="850px" :close-on-click-modal="false" :close-on-press-escape="false" center>
      <div style="text-align: center">
        <el-transfer v-model="selectedAccounts" style="text-align: left; display: inline-block" :data="unselectAccounts" :titles="['可选账号', '已选账号']" filterable />
      </div>
      <div slot="footer">
        <el-button @click="dialogTransferVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitStationAccountAuth">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dialogTitleMap[dialogStatus]" :visible.sync="dialogFormVisible" top="10vh" width="520px" :close-on-click-modal="false" :close-on-press-escape="false" center>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" class="form-center">
        <el-form-item label="企业名称" prop="companyId">
          <el-select v-model="temp.companyId" clearable filterable placeholder="请选择企业">
            <el-option
              v-for="item in companyOptions"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="站点类型" prop="stationType">
          <el-select v-model="temp.stationType" placeholder="站点类型" clearable>
            <el-option v-for="item in stationTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="站点编号" prop="stationNo">
          <el-input v-model="temp.stationNo" maxlength="128" />
        </el-form-item>
        <el-form-item label="站点名称" prop="stationName">
          <el-input v-model="temp.stationName" maxlength="128" />
        </el-form-item>
        <el-form-item label="站点地址" prop="stationAddress">
          <el-input v-model="temp.stationAddress" maxlength="128" />
        </el-form-item>
        <el-form-item label="上级站点" prop="pId">
          <el-select v-model="temp.pId" clearable filterable placeholder="请选择上级站点">
            <el-option
              v-for="item in stationOptions"
              :key="item.stationId"
              :label="item.stationName"
              :value="item.stationId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="归属省份" prop="province">
          <el-select v-model="temp.province" clearable filterable placeholder="请选择归属省份">
            <el-option
              v-for="item in provinceOptions"
              :key="item.province"
              :label="item.province"
              :value="item.province"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="归属城市" prop="city">
          <el-select v-model="temp.city" clearable filterable placeholder="请选择归属城市">
            <el-option
              v-for="item in cityOptions"
              :key="item.companyId"
              :label="item.city"
              :value="item.city"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="启用标记" prop="enableFlag">
          <el-select v-model="temp.enableFlag" placeholder="启用标记" clearable>
            <el-option v-for="item in enableFlagOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="站点路线" prop="sLine">
          <template>
            <el-select v-model="temp.lineId" clearable filterable placeholder="请选择站点 路线">
              <el-option
                v-for="item in stationLineList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
        </template>
        </el-form-item>
        <el-form-item label="站点经度" prop="longitude">
          <el-input v-model="temp.longitude" maxlength="128" />
        </el-form-item>
        <el-form-item label="站点纬度" prop="latitude">
          <el-input v-model="temp.latitude" maxlength="128" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button :loading="submiting" type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="Excel导入站点信息" :visible.sync="uploadExcelDialogVisible" center>
      <div class="app-container">
        <el-form ref="dataForm" :rules="rules" :model="uploadTemp" label-position="right" label-width="70px" fit>
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12">
              <el-form-item label="企业名称" prop="companyId">
                <el-select v-model="uploadTemp.companyId" clearable filterable placeholder="请选择企业">
                  <el-option
                    v-for="item in companyOptions"
                    :key="item.companyId"
                    :label="item.companyName"
                    :value="item.companyId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-upload
          ref="upload"
          action="customized"
          :limit="1"
          accept=".xls,.xlsx"
          :http-request="handleExcelUpload"
          :auto-upload="false"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button :loading="fileUploading" style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
          <el-button style="margin-left: 10px;" size="small" type="info" @click="handleDownloadTemplate">下载模板</el-button>
          <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>
        </el-upload>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getSmskStationList, createSmskStationInfo, updateSmskStationInfo, deleteSmskStationInfo, exportStationTemplate, importStation, updateStationAccount, getStationAccounts } from '@/api/smsk/station'
import { fetchDictMap } from '@/api/base/common'
import { selectCompanyList } from '@/api/smsk/company'
import { selectStationList } from '@/api/smsk/station'
import Pagination from '@/components/Pagination'
import { setOptionData, valueFormate } from '@/utils/dict'
import { isDecimal } from '@/utils/math'
import { saveRespExcel } from '@/utils'

export default {
  name: 'SmskStation',
  components: { Pagination },
  data() {
    const decimalValidator = (rule, value, callback) => {
      if (value && !isDecimal(value)) {
        callback(new Error())
      } else {
        callback()
      }
    }

    return {
      dialogTransferVisible: false,
      unselectAccounts: [],
      selectedAccounts: [],
      enableFlagOptions: [],
      companyOptions: [],
      stationOptions: [],
      stationTypeOptions: [],
      provinceOptions: [{
        province: '福建省'
      }],
      cityOptions: [{
        city: '福州市'
      }],
      list: [],
      total: 0,
      listLoading: false,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        companyId: null,
        enableFlag: '',
        stationNo: '',
        stationName: '',
        province: '',
        city: '',
        sortField: undefined,
        sortOrder: undefined
      },
      temp: {
        id: null,
        companyId: null,
        stationNo: '',
        stationName: '',
        stationAddress: '',
        longitude: '',
        latitude: '',
        province: '',
        city: '',
        enableFlag: '',
        pId: null,
        stationType: ''
      },
      dialogTitleMap: {
        create: '新建上门收款站点信息',
        update: '更新上门收款站点信息'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        companyId: [{ required: true, message: '企业名称不能为空', trigger: 'change' }],
        stationType: [{ required: true, message: '站点类型不能为空', trigger: 'change' }],
        stationNo: [{ required: true, message: '站点编号不能为空', trigger: 'change' }],
        stationName: [{ required: true, message: '站点名称不能为空', trigger: 'change' }],
        stationAddress: [{ required: true, message: '站点地址不能为空', trigger: 'change' }],
        province: [{ required: true, message: '归属省份不能为空', trigger: 'change' }],
        city: [{ required: true, message: '归属城市不能为空', trigger: 'change' }],
        enableFlag: [{ required: true, message: '启用标记不能为空', trigger: 'change' }],
        latitude: [{ 'validator': decimalValidator, message: '纬度格式不正确', trigger: 'change' }],
        longitude: [{ 'validator': decimalValidator, message: '经度格式不正确', trigger: 'change' }]
      },
      downloadLoading: false,
      fileUploading: false,
      uploadTemp: { companyId: null },
      uploadExcelDialogVisible: false,
      submiting: false,
      stationLineList:[]
    }
  },
  watch: {
    'temp.companyId': function(newVal, oldVal) {
      console.log(newVal)
      if (newVal) {
        this.getStationList(newVal)
      }
    }
  },
  created() {
    this.initDictInfos()
    fetchDictMap('SMSK_STATION_LINE').then(res=>{
      this.stationLineList = res.data.SMSK_STATION_LINE;
    }, response => {
        console.log(response);
      })
    // 加载下拉数据
    const optionsMap = new Map()
    optionsMap.set('YES_OR_NO', this.enableFlagOptions)
    optionsMap.set('SMSK_STATION_TYPE', this.stationTypeOptions)
    setOptionData(optionsMap)
    this.getList()
  },
  methods: {
    formatter(row, column, cellValue, index) {
      return valueFormate(this, column.property, cellValue)
    },
    initDictInfos() { // 初始化数据字典
      // 加载下拉数据
      selectCompanyList().then(res => {
        this.companyOptions = res.data
      })
    },
    getStationList(companyId) {
      selectStationList(companyId).then(res => {
        this.stationOptions = res.data
      })
    },
    getList() {
      this.listLoading = true
      getSmskStationList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      }, response => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = {
        companyId: null,
        enableFlag: '',
        stationNo: '',
        stationName: '',
        province: '',
        city: '',
        stationType: ''
      }
    },
    sortChange(data) {
      const { prop, order } = data
      this.sortByField(prop, order)
    },
    sortByField(prop, order) {
      if (order === 'ascending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'asc'
      } else if (order === 'descending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'desc'
      } else {
        this.listQuery.sortField = undefined
        this.listQuery.sortOrder = undefined
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: null,
        companyId: null,
        stationNo: '',
        stationName: '',
        stationAddress: '',
        longitude: '',
        latitude: '',
        province: '',
        city: '',
        enableFlag: '',
        pId: null,
        stationType: ''
      }
    },
    handleUpload() {
      this.uploadExcelDialogVisible = true
      this.uploadTemp = { companyId: null }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.submiting = true
          createSmskStationInfo(this.temp).then(response => {
            this.submiting = false
            this.dialogFormVisible = false
            this.getList()
            this.$message({
              message: '站点信息保存成功!',
              type: 'success'
            })
          }, () => {
            this.submiting = false
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.submiting = true
          updateSmskStationInfo(this.temp).then(response => {
            this.submiting = false
            this.getList()
            this.dialogFormVisible = false
            this.$message({
              message: '站点信息更新成功!',
              type: 'success'
            })
          }, () => {
            this.submiting = false
          })
        }
      })
    },
    handleDelete(row) {
      this.$msgbox({
        type: 'warning',
        title: '确认',
        message: '确认删除站点[' + row.stationNo + row.stationName + ']?',
        showCancelButton: true,
        showClose: false,
        closeOnPressEscape: false,
        closeOnClickModal: false,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            deleteSmskStationInfo(row.id).then((response) => {
              this.getList()
              this.$message({
                message: '站点[' + row.stationNo + row.companyName + ']删除成功!',
                type: 'success'
              })
              done()
              instance.confirmButtonLoading = false
            }, (response) => {
              done()
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        }
      })
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleExcelUpload(file) {
      if (!file || !file.file) {
        return function() {
          Promise.resolve(file)
        }
      }
      this.fileUploading = true
      importStation(file, this.uploadTemp).then(response => {
        this.getList()
        this.$message({
          message: '批量导入站点信息成功!',
          type: 'success'
        })
        this.uploadExcelDialogVisible = false
        this.fileUploading = false
      }, response => {
        this.fileUploading = false
      })
    },
    handleDownloadTemplate() {
      this.downloadLoading = true
      exportStationTemplate().then(response => {
        saveRespExcel(response)
        this.downloadLoading = false
      }, response => {
        this.downloadLoading = false
      })
    },
    handleAccounts(row) {
      this.unselectAccounts = []
      this.selectedAccounts = []
      this.selectedStationId = row.id
      getStationAccounts(row.companyId, row.id).then(response => {
        for (const v of response.data.allValidAccounts) {
          this.unselectAccounts.push({
            key: v.id,
            label: v.accountName + v.accountNo + v.subAccountNo,
            disabled: false
          })
        }
        for (const stationAccount of response.data.stationAccounts) {
          if (stationAccount && stationAccount.accountId) {
            this.selectedAccounts.push(stationAccount.accountId)
          }
        }
      })
      this.dialogTransferVisible = true
    },
    submitStationAccountAuth() {
      updateStationAccount(this.selectedStationId, JSON.stringify(this.selectedAccounts)).then(response => {
        this.dialogTransferVisible = false
        this.selectedStationId = null
        this.unselectAccounts = []
        this.selectedAccounts = []
      })
    }
  }
}
</script>
<style>
  .el-transfer-panel{
    width: 300px !important;
  }
</style>
